package com.example.zhanghao.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.zhanghao.DTO.UserDto;
import com.example.zhanghao.Entity.User;
import com.example.zhanghao.VO.CommonVo;
import com.example.zhanghao.VO.UserVo;
import com.example.zhanghao.services.CaptchaService;
import com.example.zhanghao.services.impl.UserServiceImpl;
import com.example.zhanghao.utils.CopyUtil;
import com.example.zhanghao.utils.SnowFlake;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.concurrent.TimeUnit;


@RestController //这是返回接口
@RequestMapping("/user")
public class UserController {

    private static final Logger LOG = LoggerFactory.getLogger(UserController.class);
    private final UserServiceImpl userServiceImpl;

    @Resource
    private RedisTemplate redisTemplate;
    @Autowired
    private ObjectMapper objectMapper;

    public UserController(UserServiceImpl userServiceImpl) {
        this.userServiceImpl = userServiceImpl;
    }

    @Resource
    CaptchaService captchaService;

    @Resource
    private SnowFlake snowFlake;

    @Autowired
    JavaMailSender javaMailSender;

    @PostMapping("/register")
    public CommonVo<UserVo> register(@Valid @RequestBody UserDto req){
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, req.getUsername())
                .or()
                .eq(User::getEmail, req.getEmail());

        List<User> user = userServiceImpl.list(queryWrapper);

        if(!captchaService.validateCaptcha(req.getCaptchaSessionId(),req.getCode())){
            throw new RuntimeException("验证码错误");
        } else if(!user.isEmpty()){
            throw new RuntimeException("账号或者邮箱已存在");
        }else{

            req.setName(req.getUsername());
            CommonVo<UserVo> resp= new CommonVo<>();
            userServiceImpl.saveOrUpdate(CopyUtil.copy(req, User.class));
            resp.setData(CopyUtil.copy(req, UserVo.class));
            return resp;
        }   
    }

    @PostMapping("/login")
    public CommonVo<UserVo> login(@Valid @RequestBody UserDto req){
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(User::getUsername, req.getUsername())
                .eq(User::getPassword, req.getPassword());

        User user = userServiceImpl.getOne(queryWrapper);

        if(!captchaService.validateCaptcha(req.getCaptchaSessionId(),req.getCode())){
            throw new RuntimeException("验证码错误");
        } else if(user == null){
            throw new RuntimeException("用户名不存在或密码错误");
        }else{
            UserVo userVo =  CopyUtil.copy(user, UserVo.class);
            Long id = snowFlake
                    .nextId();

            userVo.setToken(id.toString());

            redisTemplate.opsForValue().set(id, JSONObject.toJSONString(userVo),3600*240, TimeUnit.SECONDS);

            CommonVo<UserVo> resp= new CommonVo<>();
            resp.setData(userVo);
            return resp;
        }
    }

    @PostMapping("/forgot")
    public CommonVo<UserVo> forgot(@Valid @RequestBody UserDto req){
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmail, req.getEmail());

        User user = userServiceImpl.getOne(queryWrapper);

        if(!captchaService.validateCaptcha(req.getCaptchaSessionId(),req.getCode())){
            throw new RuntimeException("验证码错误");
        } else if(user == null){
            throw new RuntimeException("用户邮箱不存在");
        }else{
            // 简单邮件直接构建一个 SimpleMailMessage 对象进行配置并发送即可
            SimpleMailMessage simpMsg = new SimpleMailMessage();
            simpMsg.setFrom("2661775330@qq.com");
            simpMsg.setTo(req.getEmail());
            simpMsg.setCc("2661775330@qq.com");
            simpMsg.setSubject("找回密码");
            simpMsg.setText("账号:"+ user.getUsername() + " 密码:" + user.getPassword());
            javaMailSender.send(simpMsg);

            CommonVo<UserVo> resp= new CommonVo<>();
            resp.setData(CopyUtil.copy(req, UserVo.class));
            return resp;
        }
    }


    @GetMapping("/getUser")
    public CommonVo<UserVo> getUser(HttpServletRequest request) throws JsonProcessingException {

        String token = request.getHeader("token");

        Object redisData = redisTemplate.opsForValue().get(Long.parseLong(token));
        if (redisData == null) {
            throw new RuntimeException("请重新登录");
        } else {

            // 使用ObjectMapper将字符串转换为User对象
            User redisUser;
            if (redisData instanceof String) {
                redisUser = objectMapper.readValue((String) redisData, User.class);
            } else {
                // 如果存储的不是字符串，尝试直接转换
                redisUser = objectMapper.convertValue(redisData, User.class);
            }

            LambdaQueryWrapper<User> userQueryWrapper = new LambdaQueryWrapper<>();
            userQueryWrapper.eq(User::getId, redisUser.getId());
            User user = userServiceImpl.getOne(userQueryWrapper);
            CommonVo<UserVo> resp = new CommonVo<>();
            UserVo userVo =  CopyUtil.copy(user, UserVo.class);
            userVo.setToken(token);
            resp.setData(userVo);
            return resp;
        }
    }
}

